from django.shortcuts import render
from django.views import View
from django import http
from apps.houses.models import House, Area, Facility, HouseImage
from ihome_project.utils.view import LoginRequiredMixin
from ihome_project.libs.qiniuyun.qiniuyun_upload import storage
from django.db import transaction
from django.conf import settings
from apps.orders.models import Order
import json
from apps.users.models import User
from django.core.cache import cache


# Create your views here.


class HouseDetailView(View):
    """房屋详情页"""

    def get(self, request, house_id):
        house = House.objects.get(pk=house_id)
        house_images = HouseImage.objects.filter(house_id=house_id)
        orders = Order.objects.filter(house_id=house_id)
        user = User.objects.get(id=house.user_id)

        comments_list = []
        img_urls = []
        facility = []
        for house_image in house_images:
            img_urls.append(settings.QNY_HOST + str(house_image.url))
        for order in orders:
            comments_list.append({
                'comment': order.comment,
                'ctime': order.create_time,
                'user_name': request.user.username
            })

        for temp in house.facility.all():
            facility.append(temp.id)

        data = {
            "house": {
                "acreage": house.acreage,
                "address": house.address,
                "beds": house.beds,
                "capacity": house.capacity,
                "comments": comments_list,
                "deposit": house.deposit,
                "facilities": facility,
                "hid": house.id,
                "img_urls": img_urls,
                "max_days": house.max_days,
                "min_days": house.min_days,
                "price": house.price,
                "room_count": house.room_count,
                "title": house.title,
                "unit": house.unit,
                "user_avatar": str(user.avatar),
                "user_id": user.id,
                "user_name": user.username
            },
            "user_id": request.user.id
        }
        return http.JsonResponse({
            'errno': '0',
            'errmsg': 'ok',
            'data': data
        })


# # 3.3 上传图片类视图
class UploadPictureView(LoginRequiredMixin, View):

    def post(self, request, house_id):
        # 接收图片
        house_image_file = request.FILES.get('house_image')

        # 校验图片是否存在

        if not house_image_file:
            return http.JsonResponse({
                'errno': '4002',
                'errmsg': 'NODATA无数据'
            })
        # 检验是否是图片呢格式

        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return http.JsonResponse({
                'code': '4003',
                'errmsg': '房屋数据不存在'
            })

        # 使用骑牛上传图片
        house_image_file_data = house_image_file.read()

        try:
            flag = storage(house_image_file_data)
        except Exception as e:
            return http.JsonResponse({
                'code': '4301',
                'errmsg': '图片上传失败'
            })

        # 原子性
        with transaction.atomic():
            start_id = transaction.savepoint()  # 回滚起始ID
            try:
                if not house.index_image_url:
                    house.index_image_url = flag
                    house.save()

                house_image = HouseImage()
                house_image.house = house
                house_image.url = flag
                house_image.save()
            except Exception as e:
                # 不成功就回滚
                transaction.savepoint_rollback(start_id)
            # 成功就不需要只一个了
            transaction.savepoint_commit(start_id)
        data = {
            'url': settings.QNY_HOST + str(flag)
        }

        return http.JsonResponse({
            'data': data,
            'errno': '0',
            'errmsg': '图片上传成功'
        })


class IssueHousesView(View):
    """发布房源"""

    def post(self, request):

        # 判断是否登录
        if not request.user.is_authenticated:
            return http.JsonResponse({
                'errno': 4004,
                'errmsg': '未登录'
            })
        # 接收参数
        user = request.user
        data = json.loads(request.body)
        title = data.get('title')
        price = data.get('price')
        area_id = data.get('area_id')
        address = data.get('address')
        room_count = data.get('room_count')
        acreage = data.get('acreage')
        unit = data.get('unit')
        capacity = data.get('capacity')
        beds = data.get('beds')
        deposit = data.get('deposit')
        min_days = data.get('min_days')
        max_days = data.get('max_days')
        facility = data.get('facility')

        # 校验参数
        if not all([title, price, area_id, address, room_count, acreage, unit, capacity,
                    beds, deposit, min_days, facility]):
            return http.JsonResponse({
                'errno': '4103',
                'errmsg': '缺少必传参数！'
            })

        # 创建房源
        user = request.user
        try:
            house = House.objects.create(
                title=title,
                price=price,
                area_id=area_id,
                address=address,
                room_count=room_count,
                acreage=acreage,
                unit=unit,
                capacity=capacity,
                beds=beds,
                deposit=deposit,
                min_days=min_days,
                max_days=max_days,
                user_id=user.id
            )
        except Exception as e:
            print(e)
            return http.JsonResponse({'errno': '4001', 'errmsg': '创建房源失败'})

        # 选择设施
        facilitys = Facility.objects.filter(id__in=facility)

        # 为房间添加设施
        house.facility.add(*facilitys)

        # 返回响应
        return http.JsonResponse({
            'errno': '0',
            'errmsg': 'ok',
            'data': {
                'house_id': house.id
            }
        })

    def get(self, request):
        """搜索视图"""
        # 获取area_id
        area_id = request.GET.get('aid')
        page = request.GET.get('p')

        # 获取房源
        houses = House.objects.filter(area_id=area_id)

        data = {}
        data['houses'] = []
        for house in houses:
            # 获取用户
            user = User.objects.get(id=house.user_id)
            area = Area.objects.get(id=house.area_id)
            data['houses'].append({
                'address': house.address,
                'area_naem': area.name,
                'house_id': house.id,
                'img_url': settings.QNY_HOST + str(house.index_image_url),
                'order_count': house.order_count,
                'price': house.price,
                'room_count': house.room_count,
                'title': house.title,
                'user_avatar': str(user.avatar)
            })

        # 构建响应数据
        data['total_page'] = page

        return http.JsonResponse({
            'data': data,
            'errmsg': 'ok',
            'errno': '0'
        })


# 3.1 城区列表类视图
class AreaListView(View):

    def get(self, request):

        # 判断是否有缓存
        area_list = cache.get('area_list')

        # 接收数据
        # 没有缓存
        if not area_list:
            try:
                area_model_list = Area.objects.all()

                area_list = []
                for area_model in area_model_list:
                    area_list.append({
                        'aid': area_model.id,
                        'aname': area_model.name
                    })
                # 增加到缓存里面
                cache.set('area_list', area_list, 3600)
            except Exception as e:
                return http.JsonResponse({
                    'code': '4001',
                    'errmsg': '数据库查询错误'
                })

        # 有缓存
        response = http.JsonResponse({
            'errno': 0,
            'errmsg': '获取成功',
            'data': area_list
        })

        return response


class HouseIndexDisplayView(View):
    """首页展示"""

    def get(self, request):
        # 获取5个房屋数据
        houses = House.objects.all()[10: 15]
        data = []
        for house in houses:
            data.append({
                'house_id': house.id,
                'img_url': settings.QNY_HOST + str(house.index_image_url),
                'title': house.title
            })

        return http.JsonResponse({
            'data': data,
            'errmsg': 'ok',
            'errno': 0
        })


class HouseListView(LoginRequiredMixin, View):
    """房屋列表"""

    def get(self, request):
        """
        房屋列表展示
        :param request:
        :return:
        """

        user_id = request.user.id
        houses = House.objects.filter(user_id=user_id)
        data = {}
        data['houses'] = []
        for house in houses:
            area_name = Area.objects.get(id=house.area_id)
            data['houses'].append({
                'address': house.address,
                'area_name': area_name.name,
                'ctime': house.create_time,
                'house_id': house.id,
                'img_url': settings.QNY_HOST + str(house.index_image_url),
                'order_count': house.order_count,
                'price': house.price,
                'room_count': house.room_count,
                'title': house.title,
                'user_avatar': settings.QNY_HOST + str(request.user.avatar)
            })

        # 构建响应
        return http.JsonResponse({
            'data': data,
            'errmsg': 'ok',
            'errno': 0
        })
